﻿using Microsoft.AspNetCore.Authentication;
using WebHome_API.Models;

namespace WebHome_API.Middleware
{
    public class GetFileMiddleware
    {
        private static Dictionary<string, FileDownData> userIdList = new();
        private static int DownCount = 1;

        RequestDelegate _next;
        public GetFileMiddleware(RequestDelegate next)
        {
            this._next = next;
        }
        public async Task Invoke(HttpContext context)
        {
            //var path = context.Request.Path;
            //var query = context.Request.Query.ToList()[0].Key;

            //在这里拿到Token, 并检测
            if (context.Request.Path.StartsWithSegments("/GalGame"))
            {
                var userId = context.Request.Query["id"];
                if (DownNext(userId))
                {
                    await this._next(context);
                }
                else
                {
                    await context.Response.WriteAsync("资源下载次数已超上限 !");
                }
            }
            else
            {
                await this._next(context);
            }
        }

        private bool DownNext(string id)
        {
            bool ret = true;
            FileDownData data = new();
            if (userIdList.ContainsKey(id))
            {
                data = userIdList[id];
            }
            else
            {
                using (MyContext myContext = new())
                {
                    var cur = myContext.Users.FirstOrDefault(u=>u.Code == id);
                    if (cur is null)
                    {
                        return false;
                    }
                }
            }

            //判断时间(存储上限为30个)
            if(data.Count >= DownCount)
            {
                //计算回复的
                var count = (DateTime.Now - data.LastDateTime).Hours;
                data.Count = Math.Max(data.Count - count, 0);
                data.LastDateTime = DateTime.Now;
                if(data.Count >= DownCount)
                {
                    ret = false;
                }
            }
            else
            {
                data.Count += 1;
            }
            userIdList[id] = data;

            return ret;
        }
    }
}
